<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools show-before>
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import?type=employee')">{{ $t('route.import') }}</el-button>
          <el-button size="small" type="danger" @click="exportData">{{ $t('route.export') }}</el-button>
          <el-button size="small" type="primary" @click="addEmployee">{{ $t('route.employeesAdd') }}</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column width="100" type="index" label="序号" sortable />
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column width="150" label="头像" align="center" prop="staffPhoto">
            <img slot-scope="{ row }" v-imagerror="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" style="width: 50px" @click="openShowCodeDialog(row.staffPhoto)" />
          </el-table-column>
          <el-table-column width="150" label="手机号码" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column width="150" label="聘用形式" sortable :formatter="formatEmployment" prop="formOfEmployment" />
          <el-table-column width="150" label="部门" sortable prop="departmentName" />
          <el-table-column width="150" label="入职时间" sortable prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate('yyyy-MM-dd hh:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column width="120" label="在职状态" prop="enableState" :formatter="formatEnableState" />
          <el-table-column width="120" label="账号状态" prop="inServiceStatus">
            <template slot-scope="{ row }">
              <el-switch :value="row.inServiceStatus" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280" align="center">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="openRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
              <el-button size="small" type="text" @click="$router.push(`/employees/print/${row.id}?type=personal`)">打印员工基本信息</el-button>
              <el-button size="small" type="text" @click="$router.push(`/employees/print/${row.id}?type=job`)">打印员工岗位信息信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination :total="total" :current-page="query.page" :page-size="query.size" layout="prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-row>
      </el-card>
    </div>
    <!-- 显示头像二维码的对话框 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog" @opened="showQrCode" @close="imgUrl = ''">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 新增员工 -->
    <add-employee ref="addEmployeeRef" @get-new-employee="getEmployeeList" />
    <!-- 分配角色 -->
    <assign-role ref="assignRoleRef" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 导入常量配置对象
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
// 导入过滤器函数
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 员工列表数据
      employeeList: [],
      query: {
        page: 1,
        size: 5
      },
      total: 0,
      // 图片二维码对话框
      showCodeDialog: false,
      // 待生成二维码的图片地址
      imgUrl: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 打开角色分配对话框
    openRoleDialog(userId) {
      this.$refs.assignRoleRef.open(userId)
    },
    // 打开图片二维码对话框
    openShowCodeDialog(photo) {
      console.log(photo)
      this.imgUrl = photo
      this.showCodeDialog = true
    },

    // 监听图片二维码对话框的打开事件
    showQrCode() {
      // 生成图片二维码
      QrCode.toCanvas(
        this.$refs.myCanvas,
        'https://www.npmjs.com/npm-avatar/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdmF0YXJVUkwiOiJodHRwczovL3MuZ3JhdmF0YXIuY29tL2F2YXRhci8xMzJlNGQ4M2JiY2MzYjllNTNiNzZkMjQxMDI1NDgxYj9zaXplPTQ5NiZkZWZhdWx0PXJldHJvIn0.WaoAR5wzkWTt-M-kYsb_ta8JnREMyOeVmZWfssoqDP4'
      )
      // QrCode.toDataURL(this.$refs.myCanvas, 'https://www.kuaijiankj.com')
      // QrCode.toCanvas(this.$refs.myCanvas, 'https://www.kuaijiankj.com')
      // QrCode.toDataURL(this.$refs.myCanvas, '我来测试qrcode')
    },

    // 导出员工数据成excel表格
    async exportData() {
      // 定义中文表头和英文字段的对应关系
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      // 获取要导出的数据   [{username:'张三',mobile:'1772788888'},{username:'李四',mobile:'19277777777'}]
      const { rows } = await getEmployeeList({ page: 1, size: this.total })
      const data = this.formatJson(headers, rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: Object.keys(headers), // ['姓名','手机号码']
          data, // [['张三','1772788888'],['李四','19277777777']]
          filename: '员工信息表',
          // 复杂表头
          multiHeader: [['手机号码', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2']
        })
      })
    },
    // 处理待导出的数据
    formatJson(headers, rows) {
      // 实际： [{username:'张三',mobile:'1772788888'},{username:'李四',mobile:'19277777777'}]
      // 目标: [['张三','1772788888'],['李四','19277777777']]
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'formOfEmployment') {
            // 聘用形式的处理
            return this.formatEmployment(item)
          } else if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 入职时间和转正时间的处理(使用过滤器中格式化时间日期对象的函数)
            return formatDate(item[headers[key]], 'yyyy-MM-dd hh:mm:ss')
          } else {
            return item[headers[key]]
          }
        })
      })
    },
    // 获取员工列表数据
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.query)
      console.log(rows)
      console.log(total)
      this.employeeList = rows
      this.total = total
    },
    // 当前页码发生改变时
    handleCurrentChange(page) {
      this.query.page = page
      this.getEmployeeList()
    },
    // 每页显示条数改变时
    handleSizeChange(size) {
      this.query.size = size
      this.getEmployeeList()
    },
    // 使用formatter的方式：处理聘用形式
    formatEmployment(row) {
      const result = EmployeeEnum.hireType.find(item => item.id === row.formOfEmployment)
      return result ? result.value : '聘用形式未知'
    },
    // 处理在职状态
    formatEnableState(row) {
      const result = EmployeeEnum.workingState.find(item => +item.id === row.enableState)
      return result ? result.value : '未知转态'
    },
    // 删除员工
    async delEmployee(id) {
      try {
        await this.$confirm('您确定要删除该员工吗')
        // 删除
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch {
        console.log('取消删除')
      }
    },
    // 打开对话框
    addEmployee() {
      this.$refs.addEmployeeRef.open()
    }
  }
}
</script>

<style></style>
